package com.hdu.mockService.utils;

import lombok.val;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class ReflectionUtils {


    public static List<Field> getFieldsByTargetAnnotation(Class<?> clazz, Class<? extends Annotation> targetAnnotation) {
        validateInput(clazz, targetAnnotation);
        return filterFieldsByTargetAnnotation(clazz, targetAnnotation);
    }


    /**
     * 过滤出标记了 targetAnnotation 注解的字段
     */
    private static List<Field> filterFieldsByTargetAnnotation(Class<?> aClazz, Class<? extends Annotation> targetAnnotation) {
        val declaredFields = aClazz.getDeclaredFields();
        return Arrays.stream(declaredFields)
                .filter(declaredField -> Objects.nonNull(declaredField.getAnnotation(targetAnnotation)))
                .collect(Collectors.toList());
    }

    private static void validateInput(Class<?> clazz, Class<? extends Annotation> targetAnnotation) {
        PredictionUtils.unValidParam(
                clazz == null || targetAnnotation == null,
                "clazz or targetAnnotation is null"
        );
    }

}
